<template>
	<view class="addDiet" :style="{ paddingTop: paddingHeight + 'px' }">
		<nav-bar :title="barTitle"></nav-bar>
		<view class="header">
			<u-search
				:showAction="true"
				bgColor="#F3F4F7"
				height="76rpx"
				shape="square"
				actionText="搜索"
				:animation="true"
				clearabled
				placeholder="请输入食物名称"
				v-model="searchFood"
				@search="handleGetFoodList"
				@change="handleGetFoodList"
				@clear="dataList.length = 0"
				@custom="handleGetFoodList"
			></u-search>
		</view>
		<view class="con">
			<u-list :height="wHeight">
				<u-list-item v-for="(item, index) in dataList" :key="index">
					<view class="food-item">
						<view class="l">
							<view class="food-name">{{ item.foodName }}</view>
							<view class="food-kj">
								<text class="text1"
									>{{ item.energyContentTitle }}KJ</text
								>
								<text class="text2">/100G</text>
							</view>
						</view>
						<view class="r" @click="handleShouPopup(item)">
							<u-icon
								size="25"
								name="http://oss.antaimedical.com/images/pro/2025/02/67c028e2e4b0be9d44423450QcbTvacOyJhZ943d052cb0774cf717b8852b37cd44c0.png"
							></u-icon>
						</view>
					</view>
				</u-list-item>
			</u-list>
		</view>
		<view class="fixed-box">
			<view class="l" @click=" popupShow2 = true">
				<view class="icon">
					<u-icon
						size="32"
						:name="foodList.length ? foodIcon[1] : foodIcon[0]"
					></u-icon>
				</view>
				<view class="text-box">
					<view class="text1">已添加{{ foodList.length }}项食物</view>
					<view class="text2">{{ heatNum }}KJ</view>
				</view>
			</view>
			<view class="r" @click="handleBack()"> 记录 </view>
		</view>
		<u-popup
			:show="popupShow"
			round="20"
			mode="bottom"
			:safeAreaInsetBottom="true"
		>
			<view class="popup-con">
				<view class="popup-header">
					<view class="l">
						<text>{{ foodObj.foodName }}</text>
						<text>{{ foodObj.energyContentTitle }}KJ/100g</text>
					</view>
					<view class="r" @click="popupShow = false">
						<u-icon size="18" name="close"></u-icon>
					</view>
				</view>
				<view class="popup-box">
					<view class="con">
						<view class="item">
							<view class="t">{{ foodObj.heat || 0 }}</view>
							<view class="b">热量(g)</view>
						</view>
						<view class="item">
							<view class="t">{{
								foodObj.carbohydrate || 0
							}}</view>
							<view class="b">碳水(g)</view>
						</view>
						<view class="item">
							<view class="t">{{ foodObj.fat || 0 }}</view>
							<view class="b">脂肪(g)</view>
						</view>
						<view class="item">
							<view class="t">{{ foodObj.protein || 0 }}</view>
							<view class="b">氨基酸(g)</view>
						</view>
					</view>
					<view class="input-box">
						<view class="input-value">
							<u--input
								type="number"
								fontSize="22"
								border="bottom"
								placeholderStyle="color:#1F2434;font-size:58rpx;"
								@change="handleChangeKJ"
								v-model="foodObj.gram"
								:cursorSpacing="110"
							>
							</u--input>
						</view>
						<view class="text">克</view>
					</view>
					<view class="save-btn" @click="handleSave">确认</view>
				</view>
			</view>
		</u-popup>
		<u-popup
			:show="popupShow2"
			round="20"
			mode="bottom"
			:safeAreaInsetBottom="true"
		>
			<view class="popup-con">
				<view class="popup-header2">
					<view></view>
					<view class="l">
						<text>已添加食物</text>
					</view>
					<view class="r" @click="popupShow2 = false">
						<u-icon size="18" name="close"></u-icon>
					</view>
				</view>
				<view>
					<u-list height="400">
						<u-list-item
							v-for="(item, index) in foodList"
							:key="index"
						>
							<view class="food-item">
								<view class="l" @click="handleShouPopup(item)">
									<view class="food-name">{{
										item.foodName
									}}</view>
									<view class="food-kj">
										<text class="text1"
											>{{ item.heat }}KJ</text
										>
										<text class="text2"
											>/{{ item.gram }}G</text
										>
									</view>
								</view>
								<view class="r" @click="handleDelFood(item)">
									<u-icon size="25" name="trash"></u-icon>
								</view>
							</view>
						</u-list-item>
					</u-list>
				</view>
			</view>
		</u-popup>
		<my-datetime-picker
			:show="showModal"
			@cancel="showModal = false"
			@confirm="setTime"
			mode="time"
		></my-datetime-picker>
	</view>
</template>

<script>
import myDatetimePicker from '@/components/my-datetime-picker/my-datetime-picker.vue'
import { mapGetters } from 'vuex'

import {
	addDietaryRecord,
	getFoodEnergy,
	findOneMealDietaryByType,
	updateDietaryRecord,
	addDietaryOneRecord,
	delDietaryRecord,
	getMealId,
	getFoodList
} from '@/api/index.js'
import { mergeObjOfValue } from '@/utils/utils.js'
let app = getApp()
const dayjs = require('@/utils/dayjs.min.js')

const createFood = {
	energyContentTitle: '',
	dietaryTime: '00:00',
	foodId: '',
	foodName: '',
	type: '',
	userId: '',
	carbohydrate: '',
	fat: '',
	heat: '',
	picUrl: '',
	protein: '',
	bodyId: '',
	gram: '',
	mealId: '',
	id: null
}

export default {
	data() {
		return {
			paddingHeight: uni.getStorageSync('navbarHeight'),
			userId: uni.getStorageSync('userId'),
			globalData: app.globalData,
			wHeight: '',
			type: 1,
			showModal: false,
			modalIndex: -1,
			foodList: [],
			reType: null, //1推荐  2自定义
			searchFood: '',
			dataList: [],
			popupShow: false,
			popupShow2: false,
			foodObj: {
				energyContentTitle: '',
				dietaryTime: '00:00',
				foodId: '',
				foodName: '',
				type: '',
				userId: '',
				carbohydrate: '',
				fat: '',
				heat: '',
				picUrl: '',
				protein: '',
				bodyId: '',
				gram: '',
				mealId: '',
				id: null
			},
			mealId: '',
			heatNum: 0,
			gram: '',
			foodIcon: {
				0: 'http://oss.antaimedical.com/images/pro/2025/02/67c16793e4b0be9d44423451elBdLfOGe9WG9178a1a03e0d07afc4522718f047f838.png',
				1: 'http://oss.antaimedical.com/images/pro/2025/02/67c1674ee4b0d615350f3148ghYVdkpUlnxX4401cc80d067197da509261abaeac072.png'
			}
		}
	},
	components: {
		myDatetimePicker
	},
	computed: {
		...mapGetters({
			userInfo: 'getUserInfo'
		})
	},
	onLoad(OPTIONS) {
        this.wHeight = uni.getSystemInfoSync().windowHeight - this.globalData.navBarHeight-160
		this.day = dayjs(OPTIONS.day).format('YYYY-MM-DD')
		this.reType = OPTIONS.reType
		this.type = OPTIONS.type
		createFood.dietaryTime = OPTIONS.dietaryTime
		this.getFindOneMealDietaryByType()
		this.getMealId()
	},
	methods: {
		// 获取用餐id
		getMealId() {
			let params = {
				dietaryTime: this.day,
				type: this.type,
				userId: this.userInfo.userId
			}
			getMealId(params).then((res) => {
				this.mealId = res.data
			})
		},
		// 删除食物
		handleDelFood(item) {
			delDietaryRecord({ id: item.id }).then((res) => {
				this.getFindOneMealDietaryByType()
			})
		},
		// 添加食物确认按钮
		handleSave() {
            if(!this.foodObj.heat) return
			this.foodObj.type = this.type
			this.foodObj.userId = this.userInfo.userId
			this.foodObj.bodyId = this.userInfo.bodyId
			let params = {
				...this.foodObj,
				dietaryTime: `${this.day} ${this.foodObj.dietaryTime}:00`
			}
			// 删除完食物，添加
			if (this.foodList.length == 0 && this.mealId) {
				params.mealId = this.mealId
				addDietaryOneRecord(params).then((res) => {
					this.getFindOneMealDietaryByType()
					this.popupShow = false
				})
			}
			// 修改食物
			else if (params.mealId) {
				updateDietaryRecord({ ...params }).then((res) => {
					this.getFindOneMealDietaryByType()
					this.popupShow = false
				})
				// 已经有食物添加食物
			} else if (this.foodList.length) {
				params.mealId = this.foodList[0].mealId
				addDietaryOneRecord(params).then((res) => {
					this.getFindOneMealDietaryByType()
					this.popupShow = false
				})
				// 没有食物添加食物
			} else {
				addDietaryRecord([params]).then((res) => {
					this.getFindOneMealDietaryByType()
					this.popupShow = false
				})
			}
			this.handleBack()
		},
		// 输入克获取食物其他数据
		handleChangeKJ() {
			let params = {
				foodId: this.foodObj.foodId,
				gram: this.foodObj.gram
			}
			uni.$u.debounce(this.handleGetFoodEnergy(params), 500)
		},
		// 添加,编辑食物弹窗
		handleShouPopup(item) {
			let obj = JSON.parse(JSON.stringify(createFood))
			mergeObjOfValue(obj, item)
			if (obj.mealId) {
				obj.energyContentTitle = ((obj.heat * 100) / obj.gram).toFixed()
			}
			this.foodObj = obj
			this.popupShow2 = false
			this.popupShow = true
		},
		// 搜索食物
		handleGetFoodList(val) {
            if(!val){
                this.dataList.length = 0
                return
            }
			let params = {
				foodName: this.searchFood,
				page: 1,
				size: 500
			}
			getFoodList(params).then((res) => {
				this.dataList = res.data.list.map((val) => {
					return {
						foodName: val.foodName,
						energyContentTitle: val.energyContent,
						// id: val.id,
						foodId: val.id
					}
				})
			})
		},
        handleBack(){
            uni.navigateBack()
        },
		// 获取食物列表
		getFindOneMealDietaryByType() {
			let params = {
				time: dayjs(this.day).format('YYYY-MM-DD'),
				type: this.type,
				userId: this.userInfo.userId
			}
			findOneMealDietaryByType(params).then((res) => {
				if (res.data.length) {
					let arr = []
					let num = 0
					res.data.forEach((item) => {
						num += item.heat
						let obj = JSON.parse(JSON.stringify(createFood))
						mergeObjOfValue(obj, item)
						arr.push(obj)
					})
					this.heatNum = num.toFixed(2)
					this.foodList = arr
				} else {
					this.foodList = []
				}
			})
		},
		setTime(val) {
			this.foodList[this.modalIndex].dietaryTime = val.value
			this.showModal = false
		},
		handleGetFoodEnergy(item) {
			let params = {
				foodId: item.foodId,
				gram: item.gram
			}
			getFoodEnergy(params)
				.then((res) => {
					this.foodObj.heat = res.data.energyContent
					this.foodObj.carbohydrate = res.data.carbohydratesContent
					this.foodObj.fat = res.data.fatContent
					this.foodObj.protein = res.data.proteinsContent
				})
				.catch((err) => {})
		}
	}
}
</script>

<style lang="scss">
page {
	padding-bottom: 76rpx;
	background: #fafafa;
}
</style>
<style lang="scss" scoped>
.addDiet {
	padding: 0 32rpx;
	// padding-bottom: 146rpx;
	.header {
		margin-top: 28rpx;
		margin-bottom: 10rpx;
	}
	.con {
		.food-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 0;
			border-bottom: 2rpx solid #f4f4f4;
			.l {
				display: flex;
				flex-direction: column;
				justify-content: center;
				.food-name {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #1f2434;
					line-height: 38rpx;
					text-align: left;
					margin-bottom: 10rpx;
				}
				.food-kj {
					font-weight: 400;
					font-size: 24rpx;
					color: #1f2434;
					text-align: left;
					.text2 {
						color: #9ba2b9;
					}
				}
			}
			.r {
				width: 54rpx;
				height: 54rpx;
			}
		}
	}
	.fixed-box {
		position: fixed;
		left: 0;
		bottom: 0;
		background: #fff;
		box-shadow: 0rpx 8rpx 19rpx 0rpx rgba(0, 0, 0, 0.3);
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 68rpx;
		width: 100%;
		.l {
			display: flex;
			justify-content: center;
			align-items: center;
			.text-box {
				margin-left: 26rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #1f2434;
				text-align: left;
				.text2 {
					font-size: 32rpx;
					text-align: left;
					margin-top: 10rpx;
				}
			}
		}
		.r {
			width: 228rpx;
			height: 78rpx;
			background: #1f2434;
			border-radius: 46rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #ffffff;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	.popup-con {
		padding: 26rpx 32rpx;
		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.l {
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				font-size: 28rpx;
				color: #1f2434;
				text-align: left;
			}
		}
		.popup-box {
			margin: 34rpx auto;
			.con {
				padding: 24rpx;
				background-color: #f3f4f7;
				border-radius: 12rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.item {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					.t {
						font-weight: 500;
						font-size: 32rpx;
						color: #1f2434;
						line-height: 48rpx;
						text-align: center;
					}
					.b {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 22rpx;
						color: #5a667e;
						line-height: 48rpx;
						text-align: center;
					}
				}
			}
			.input-box {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 56rpx;
				margin-bottom: 80rpx;
				.input-value {
					width: 152rpx;
				}
				.text {
					font-weight: 500;
					font-size: 32rpx;
					color: rgba(31, 36, 52, 0.5);
				}
				/deep/.u-border-bottom {
					border-bottom: 4rpx solid #1f2434 !important;
				}
			}
			.save-btn {
				width: 338rpx;
				height: 85rpx;
				background: #1f2434;
				border-radius: 46rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #ffffff;
				text-align: center;
				margin: 0 auto;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
		.popup-header2 {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		.food-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 0;
			border-bottom: 2rpx solid #f4f4f4;
			.l {
				display: flex;
				flex-direction: column;
				justify-content: center;
				.food-name {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #1f2434;
					line-height: 38rpx;
					text-align: left;
					margin-bottom: 10rpx;
				}
				.food-kj {
					font-weight: 400;
					font-size: 24rpx;
					color: #1f2434;
					text-align: left;
					.text2 {
						color: #9ba2b9;
					}
				}
			}
			.r {
				width: 54rpx;
				height: 54rpx;
			}
		}
	}
}
</style>
